/*
 * 泉城路ThingJS应用 - 优化通信版本
 * @version 2.1
 * 集成优化的Vue弹窗系统 + 改进的通信机制
 */

//version 2.0 创建app，默认绑定到 'div3d' DIV 元素
var app = new THING.App();

THING.Utils.loadFile(
  ['https://www.thingjs.com/static/historyVersion/thing.earth.umd.min.js', 'https://cdn.jsdelivr.net/npm/echarts@6.0.0/dist/echarts.min.js'],
  {
    load: function () {
      // 新建一个地图
      new THING.EARTH.Map({
        style: {
          night: false
        },
        url: 'https://city.thingjs.com/ra/city/mapProject/config/TVRVeE9EZzFOUT09Q2l0eUJ1aWxkZXJAMjAxOQ==',
        attribution: '高德',
        maximumLevel: 18
      });

      // 地图加载完成后初始化
      console.log('🗺️ ThingJS地图加载完成');
      initializeApp();
    }
  }
);

// ==================== 优化通信系统 ====================

class ThingJSMessenger {
  constructor() {
    this.pendingRequests = new Map();
    this.messageHandlers = new Map();
    this.throttleTimers = new Map();
    this.setupMessageListener();

    console.log('🎯 ThingJS优化通信系统初始化');
  }

  async sendMessage(method, data = null, options = {}) {
    const { timeout = 5000, retry = 2, expectResponse = true } = options;
    const messageId = this.generateMessageId();

    const message = {
      id: messageId,
      method,
      data,
      timestamp: Date.now(),
      source: 'ThingJS',
      type: expectResponse ? 'request' : 'notification'
    };

    if (!expectResponse) {
      this.postMessage(message);
      return Promise.resolve(null);
    }

    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        const pending = this.pendingRequests.get(messageId);
        if (pending && pending.retryCount < pending.maxRetries) {
          pending.retryCount++;
          console.warn(`消息重试 ${pending.retryCount}/${pending.maxRetries}:`, method);
          this.postMessage(message);

          clearTimeout(pending.timer);
          pending.timer = setTimeout(() => {
            this.pendingRequests.delete(messageId);
            reject(new Error(`消息超时: ${method}`));
          }, timeout);
        } else {
          this.pendingRequests.delete(messageId);
          reject(new Error(`消息超时: ${method}`));
        }
      }, timeout);

      this.pendingRequests.set(messageId, {
        resolve,
        reject,
        timer,
        retryCount: 0,
        maxRetries: retry
      });

      this.postMessage(message);
    });
  }

  notify(method, data = null) {
    this.sendMessage(method, data, { expectResponse: false });
  }

  throttledSend(method, data = null, delay = 16) {
    if (this.throttleTimers.has(method)) {
      clearTimeout(this.throttleTimers.get(method));
    }

    const timer = setTimeout(() => {
      this.notify(method, data);
      this.throttleTimers.delete(method);
    }, delay);

    this.throttleTimers.set(method, timer);
  }

  onMessage(method, handler) {
    this.messageHandlers.set(method, handler);
  }

  respond(originalMessage, data = null, success = true, error = null) {
    const response = {
      id: this.generateMessageId(),
      method: originalMessage.method,
      data,
      timestamp: Date.now(),
      source: 'ThingJS',
      type: 'response',
      responseId: originalMessage.id,
      success,
      error
    };

    this.postMessage(response);
  }

  setupMessageListener() {
    window.addEventListener('message', async (event) => {
      try {
        const message = event.data;

        if (!message || !message.method) {
          return;
        }

        if (message.source === 'ThingJS') {
          return;
        }

        if (message.type === 'response') {
          this.handleResponse(message);
        } else {
          await this.handleRequest(message);
        }
      } catch (error) {
        console.error('处理消息失败:', error);
      }
    });
  }

  handleResponse(message) {
    if (!message.responseId) return;

    const pending = this.pendingRequests.get(message.responseId);
    if (pending) {
      clearTimeout(pending.timer);
      this.pendingRequests.delete(message.responseId);

      if (message.success) {
        pending.resolve(message.data);
      } else {
        pending.reject(new Error(message.error || '未知错误'));
      }
    }
  }

  async handleRequest(message) {
    const handler = this.messageHandlers.get(message.method);
    if (handler) {
      try {
        const result = await handler(message.data, message);

        if (message.type === 'request') {
          this.respond(message, result, true);
        }
      } catch (error) {
        console.error(`处理消息 ${message.method} 失败:`, error);

        if (message.type === 'request') {
          this.respond(message, null, false, error.message);
        }
      }
    } else {
      console.warn(`未找到消息处理器: ${message.method}`);

      if (message.type === 'request') {
        this.respond(message, null, false, `未找到处理器: ${message.method}`);
      }
    }
  }

  postMessage(message) {
    try {
      if (window.parent && window.parent !== window) {
        window.parent.postMessage(message, '*');
        console.log('📤 发送消息:', message.method, message.data);
      } else {
        console.warn('⚠️ 未检测到父窗口');
      }
    } catch (error) {
      console.error('发送消息失败:', error);
    }
  }

  generateMessageId() {
    return `thingjs_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  destroy() {
    this.pendingRequests.forEach((pending) => {
      clearTimeout(pending.timer);
      pending.reject(new Error('Messenger已销毁'));
    });
    this.pendingRequests.clear();

    this.throttleTimers.forEach((timer) => clearTimeout(timer));
    this.throttleTimers.clear();

    this.messageHandlers.clear();

    console.log('🗑️ ThingJS通信系统已销毁');
  }
}

// ==================== 弹窗管理器 ====================

class OptimizedPopupManager {
  constructor(app) {
    this.app = app;
    this.trackingPopups = new Map();
    this.isDragging = false;
    this.lastUpdateTime = 0;
    this.updateThrottle = 16; // 60fps
    this.rafId = null;
    this.monitorPointsMap = new Map(); // 存储各类型监测点 {monitorType: [entities]}
    this.visibleMonitorTypes = new Set(); // 当前显示的监测类型

    this.setupEventListeners();

    console.log('🎯 优化弹窗管理器初始化完成');
  }

  setupEventListeners() {
    const camera = this.app.camera;

    // 鼠标事件
    this.app.on('mousedown', (ev) => {
      if (ev.button === 0 && this.trackingPopups.size > 0) {
        this.startDragTracking();
      }
    });

    this.app.on('mousemove', (ev) => {
      if (this.isDragging && this.trackingPopups.size > 0) {
        this.handleDragMove();
      }
    });

    this.app.on('mouseup', (ev) => {
      if (this.isDragging) {
        this.endDragTracking();
      }
    });

    // 滚轮事件（缩放）
    this.app.on('mousewheel', (ev) => {
      if (this.trackingPopups.size > 0) {
        clearTimeout(this.zoomTimer);
        this.zoomTimer = setTimeout(() => {
          this.handleZoomUpdate();
        }, 50);
      }
    });

    // 相机更新 - 移除频繁触发的相机更新监听，避免无限循环
    // 注释掉相机更新监听，只在拖动和缩放时更新弹窗位置
    // if (camera && camera.on) {
    //   camera.on('update', () => {
    //     if (!this.isDragging && this.trackingPopups.size > 0) {
    //       this.handleCameraUpdate();
    //     }
    //   });
    // }

    // 窗口大小变化
    window.addEventListener('resize', () => {
      if (this.trackingPopups.size > 0) {
        setTimeout(() => {
          this.updateAllPopupPositions();
        }, 100);
      }
    });

    // 设备点击
    this.app.on('click', (ev) => {
      if (ev.object && ev.object.userData && ev.object.userData.deviceType) {
        this.handleDeviceClick(ev.object, ev.coordinates || ev.position);
      }
    });
  }

  setupMessageHandlers() {
    // 处理Vue发来的跟踪弹窗更新
    window.messenger.onMessage('更新跟踪弹窗', (trackingData) => {
      this.updateTrackingPopups(trackingData);
    });

    // 处理ping消息
    window.messenger.onMessage('ping', () => {
      return { message: 'pong', timestamp: Date.now() };
    });

    // 获取应用信息
    window.messenger.onMessage('获取应用信息', () => {
      return {
        version: '2.1',
        mapType: 'EARTH.Map',
        camera: {
          position: this.app.camera.position,
          target: this.app.camera.target,
          fov: this.app.camera.fov
        },
        capabilities: {
          popupSystem: true,
          mapFollow: true,
          deviceInteraction: true,
          optimizedCommunication: true
        }
      };
    });

    // 处理管道井数据
    window.messenger.onMessage('管道井', (data) => {
      console.log('🕳️ 开始绘制管道井模型，数据量:', data.length);
      if (data && Array.isArray(data)) {
        drawPipeWells(data);
      }
    });

    // 处理压力监测数据
    window.messenger.onMessage('压力监测', (messageData) => {
      // 解析消息数据
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换压力监测点位的显示状态
        this.toggleMonitorType('压力监测', data);
      }
    });

    // 处理餐饮场所监测数据
    window.messenger.onMessage('餐饮场所监测', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换餐饮场所监测点位的显示状态
        this.toggleMonitorType('餐饮场所监测', data);
      }
    });

    // 处理激光监测数据
    window.messenger.onMessage('激光监测', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换激光监测点位的显示状态
        this.toggleMonitorType('激光监测', data);
      }
    });

    // 处理相邻地下空间数据
    window.messenger.onMessage('相邻地下空间', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换相邻地下空间点位的显示状态
        this.toggleMonitorType('相邻地下空间', data);
      }
    });

    // 处理人口密集区数据
    window.messenger.onMessage('人口密集区', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换人口密集区点位的显示状态
        this.toggleMonitorType('人口密集区', data);
      }
    });

    // 处理扰动风险区域数据
    window.messenger.onMessage('扰动风险区域', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换扰动风险区域点位的显示状态
        this.toggleMonitorType('扰动风险区域', data);
      }
    });

    // 处理预警总数数据
    window.messenger.onMessage('预警总数', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换预警总数点位的显示状态
        this.toggleMonitorType('预警总数', data);
      }
    });

    // 处理事件处置数据
    window.messenger.onMessage('事件处置', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换事件处置点位的显示状态
        this.toggleMonitorType('事件处置', data);
      }
    });

    // 处理预警概况数据
    window.messenger.onMessage('预警概况', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换预警概况点位的显示状态
        this.toggleMonitorType('预警概况', data);
      }
    });

    // 处理设备告警概况数据
    window.messenger.onMessage('设备告警概况', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换设备告警概况点位的显示状态
        this.toggleMonitorType('设备告警概况', data);
      }
    });

    // 处理告警类型统计数据
    window.messenger.onMessage('告警类型统计', (messageData) => {
      const { data, type } = messageData;

      if (data && Array.isArray(data)) {
        // 切换告警类型统计点位的显示状态
        this.toggleMonitorType('告警类型统计', data);
      }
    });
  }

  updateTrackingPopups(trackingData) {
    console.log('📥 收到跟踪弹窗更新:', trackingData);
    this.trackingPopups.clear();

    if (Array.isArray(trackingData)) {
      trackingData.forEach((popup) => {
        console.log('🔍 处理弹窗ID:', popup.id);
        console.log('🔍 弹窗数据:', popup);

        if (popup.id && popup.geoPosition) {
          // 尝试查找对应的实体
          let entity = null;

          // 首先显示当前 monitorPointsMap 的状态
          console.log('🔍 当前monitorPointsMap keys:', Array.from(this.monitorPointsMap.keys()));

          // 方法1: 通过监测类型查找 (如果ID包含下划线)
          if (this.monitorPointsMap && popup.id.includes('_')) {
            const monitorType = popup.id.split('_')[0];
            console.log('🔍 从ID提取的监测类型:', monitorType);
            const entities = this.monitorPointsMap.get(monitorType);
            console.log('🔍 该类型的实体数组:', entities ? entities.length : 0);
            if (entities && Array.isArray(entities)) {
              entities.forEach((e, index) => {
                console.log(`  实体${index} userData:`, e.userData);
              });
              entity = entities.find((e) => e.userData && e.userData.id === popup.id);
              console.log('🔍 通过监测类型找到匹配实体:', !!entity);
            }
          }

          // 方法2: 如果方法1没找到，遍历所有监测类型查找
          if (!entity && this.monitorPointsMap) {
            console.log('🔍 方法1未找到，开始遍历所有监测类型');
            for (const [monitorType, entities] of this.monitorPointsMap) {
              if (entities && Array.isArray(entities)) {
                entity = entities.find((e) => e.userData && e.userData.id === popup.id);
                if (entity) {
                  console.log('✅ 在监测类型', monitorType, '中找到匹配实体');
                  break;
                }
              }
            }
          }

          this.trackingPopups.set(popup.id, {
            geoPosition: popup.geoPosition,
            currentPosition: popup.currentPosition || popup.position || { x: 0, y: 0 },
            entity: entity // 存储实体引用
          });
          console.log('✅ 弹窗已添加到跟踪:', popup.id, !!entity);
        }
      });
    }

    console.log('📊 跟踪弹窗总数:', this.trackingPopups.size);
  }

  startDragTracking() {
    this.isDragging = true;
    window.messenger.notify('地图拖动开始');
    console.log('🖱️ 开始地图拖动跟踪');
  }

  handleDragMove() {
    const now = Date.now();

    if (now - this.lastUpdateTime >= this.updateThrottle) {
      this.updateAllPopupPositions('地图拖动中');
      this.lastUpdateTime = now;
    } else {
      if (!this.rafId) {
        this.rafId = requestAnimationFrame(() => {
          this.updateAllPopupPositions('地图拖动中');
          this.lastUpdateTime = Date.now();
          this.rafId = null;
        });
      }
    }
  }

  endDragTracking() {
    this.isDragging = false;

    if (this.rafId) {
      cancelAnimationFrame(this.rafId);
      this.rafId = null;
    }

    this.updateAllPopupPositions();
    window.messenger.notify('地图拖动结束');

    console.log('🖱️ 结束地图拖动跟踪');
  }

  handleZoomUpdate() {
    this.updateAllPopupPositions('地图缩放');
  }

  // handleCameraUpdate 方法已移除，因为移除了相机更新监听
  // 现在只在地图拖动和缩放时更新弹窗位置，避免无限循环

  updateAllPopupPositions(method = '批量更新弹窗位置') {
    const updates = this.calculateAllPopupPositions();
    if (updates.length > 0) {
      // 使用节流发送，提高性能
      window.messenger.throttledSend(method, { popupPositions: updates });
    }
  }

  calculateAllPopupPositions() {
    const updates = [];

    console.log('🔍 检查跟踪弹窗数量:', this.trackingPopups.size);

    this.trackingPopups.forEach((popupData, id) => {
      console.log('📍 处理弹窗:', id, '实体存在:', !!popupData.entity);

      let screenPos = null;

      // 优先使用实体DOM位置
      if (popupData.entity) {
        screenPos = this.getEntityDOMPosition(popupData.entity);
        console.log('🎯 获取到实体位置:', screenPos);
      }
      // 如果没有实体（如测试弹窗），使用当前位置
      else if (popupData.currentPosition && popupData.currentPosition.x !== undefined) {
        screenPos = popupData.currentPosition;
        console.log('🎯 使用当前位置:', screenPos);
      } else {
        console.log('⚠️ 弹窗没有实体引用且没有当前位置:', id);
      }

      if (screenPos) {
        updates.push({
          id: id,
          position: screenPos
        });

        popupData.currentPosition = screenPos;
      }
    });

    console.log('📤 最终更新数组:', updates);
    return updates;
  }

  /**
   * 获取实体元素的DOM坐标
   */
  getEntityDOMPosition(entity) {
    try {
      console.log('🔍 开始获取实体屏幕位置');
      console.log('🔍 实体对象:', entity);

      // 方法1: 使用ThingJS的worldToScreen方法（如果可用）
      if (entity && entity.position && this.app && this.app.camera) {
        try {
          // 尝试使用ThingJS的内置坐标转换
          const worldPos = entity.position;
          console.log('🌍 实体世界坐标:', worldPos);

          // 尝试使用相机的worldToScreen方法
          if (this.app.camera.worldToScreen) {
            const screenPos = this.app.camera.worldToScreen(worldPos);
            console.log('📱 worldToScreen结果:', screenPos);
            console.log('📱 screenPos类型:', typeof screenPos);
            console.log('📱 screenPos是否为数组:', Array.isArray(screenPos));

            if (screenPos) {
              // 如果是数组格式 [x, y, z]
              if (Array.isArray(screenPos) && screenPos.length >= 2) {
                const result = { x: screenPos[0], y: screenPos[1] };
                console.log('📱 数组格式转换结果:', result);
                return result;
              }
              // 如果是对象格式 {x, y}
              else if (screenPos.x !== undefined && screenPos.y !== undefined) {
                const result = { x: screenPos.x, y: screenPos.y };
                console.log('📱 对象格式转换结果:', result);
                return result;
              }
            }
          }

          // 尝试使用app的worldToScreen方法
          if (this.app.worldToScreen) {
            const screenPos = this.app.worldToScreen(worldPos);
            console.log('📱 app.worldToScreen结果:', screenPos);
            if (screenPos && screenPos.x !== undefined && screenPos.y !== undefined) {
              return { x: screenPos.x, y: screenPos.y };
            }
          }
        } catch (error) {
          console.log('⚠️ worldToScreen方法调用失败:', error);
        }
      }

      // 方法2: 使用DOM元素的getBoundingClientRect
      if (entity && entity.domElement) {
        console.log('🔍 使用DOM元素获取位置');
        const rect = entity.domElement.getBoundingClientRect();
        console.log('📐 getBoundingClientRect:', rect);

        // 计算中心点，并考虑页面滚动
        const centerX = rect.left + rect.width / 2 + window.scrollX;
        const centerY = rect.top + rect.height / 2 + window.scrollY;

        console.log('📱 DOM计算结果:', { x: centerX, y: centerY });

        if (centerX !== 0 || centerY !== 0) {
          return { x: centerX, y: centerY };
        }
      }

      // 方法3: 检查实体是否有直接的屏幕坐标属性
      if (entity) {
        console.log('🔍 检查实体的屏幕坐标属性');
        const properties = ['screenPosition', 'screenPos', 'screen', 'clientPosition'];

        for (const prop of properties) {
          if (entity[prop] && typeof entity[prop] === 'object') {
            console.log(`📱 找到${prop}:`, entity[prop]);
            if (entity[prop].x !== undefined && entity[prop].y !== undefined) {
              return { x: entity[prop].x, y: entity[prop].y };
            }
          }
        }
      }

      console.log('⚠️ 所有方法都无法获取有效坐标');
      return null;
    } catch (error) {
      console.error('❌ 获取实体屏幕位置失败:', error);
      return null;
    }
  }

  // geoToScreen 方法已移除，现在只使用实体DOM位置

  handleDeviceClick(device, coordinates) {
    console.log('🔧 处理设备点击:', device);

    // 安全地获取坐标信息
    const safeCoordinates = Array.isArray(coordinates) ? coordinates : [];
    const safePosition = Array.isArray(device.position) ? device.position : [];

    const deviceData = {
      id: device.id,
      name: device.userData.deviceName || device.name || '燃气检测设备',
      type: device.userData.deviceType || '燃气检测仪',
      status: device.userData.status || 'online',
      location: device.userData.location || '设备位置',
      hasVideo: device.userData.hasVideo || false,
      updateTime: new Date().toISOString(),
      geoPosition: {
        longitude: safeCoordinates[0] || safePosition[0] || 0,
        latitude: safeCoordinates[1] || safePosition[1] || 0,
        height: safeCoordinates[2] || safePosition[2] || 0
      },
      followMap: true
    };

    // 发送设备详情到Vue
    window.messenger.notify('显示设备详情', deviceData);
  }

  // 便捷方法
  showDeviceDetail(deviceData) {
    if (!deviceData.geoPosition) {
      console.warn('⚠️ 设备数据缺少地理坐标信息', deviceData);
      return;
    }

    // 先关闭所有现有弹窗，确保一次只显示一个
    window.messenger.notify('关闭所有弹窗');

    // 不再进行坐标转换，直接使用传入的position
    if (deviceData.followMap === undefined) {
      deviceData.followMap = true;
    }

    window.messenger.notify('显示设备详情', deviceData);
  }

  showMonitorData(monitorData) {
    console.log('📤 showMonitorData被调用');
    console.log('📤 接收到的monitorData:', monitorData);
    console.log('📤 monitorData.position:', monitorData.position);

    if (!monitorData.geoPosition) {
      console.warn('⚠️ 监测数据缺少地理坐标信息', monitorData);
      return;
    }

    // 先关闭所有现有弹窗，确保一次只显示一个
    window.messenger.notify('关闭所有弹窗');

    // 不再进行坐标转换，直接使用传入的position
    if (monitorData.followMap === undefined) {
      monitorData.followMap = true;
    }

    console.log('📤 即将发送到Vue的数据:', monitorData);
    console.log('📤 发送前final check - position:', monitorData.position);
    window.messenger.notify('显示监测数据', monitorData);
  }

  showAlarmInfo(alarmData) {
    if (!alarmData.geoPosition) {
      console.warn('⚠️ 报警数据缺少地理坐标信息', alarmData);
      return;
    }

    // 先关闭所有现有弹窗，确保一次只显示一个
    window.messenger.notify('关闭所有弹窗');

    // 不再进行坐标转换，直接使用传入的position
    if (alarmData.followMap === undefined) {
      alarmData.followMap = true;
    }

    window.messenger.notify('显示报警信息', alarmData);
  }

  showWarningInfo(warningData) {
    if (!warningData.geoPosition) {
      console.warn('⚠️ 预警数据缺少地理坐标信息', warningData);
      return;
    }

    // 先关闭所有现有弹窗，确保一次只显示一个
    window.messenger.notify('关闭所有弹窗');

    // 不再进行坐标转换，直接使用传入的position
    if (warningData.followMap === undefined) {
      warningData.followMap = true;
    }

    window.messenger.notify('显示预警信息', warningData);
  }

  closePopup(popupId) {
    window.messenger.notify('关闭弹窗', { id: popupId });
  }

  closeAllPopups() {
    window.messenger.notify('关闭弹窗', {});
  }

  /**
   * 切换监测点类型的显示状态
   */
  toggleMonitorType(monitorType, monitorData) {
    if (this.visibleMonitorTypes.has(monitorType)) {
      // 如果已显示，则隐藏该类型的所有点位
      this.hideMonitorType(monitorType);
    } else {
      // 如果未显示，则显示该类型的所有点位
      this.showMonitorType(monitorType, monitorData);
    }
  }

  /**
   * 显示指定类型的监测点
   */
  showMonitorType(monitorType, monitorData) {
    console.log(`🔍 显示${monitorType}监测点, 数量:`, monitorData.length);

    if (!Array.isArray(monitorData)) {
      console.warn('⚠️ 监测数据不是数组:', monitorData);
      return;
    }

    // 先清除该类型的现有点位
    this.hideMonitorType(monitorType);

    const entities = [];

    monitorData.forEach((monitorItem, index) => {
      if (monitorItem.longitude && monitorItem.latitude) {
        const entity = this.createMonitorPoint(monitorItem, monitorType, index);
        if (entity) {
          entities.push(entity);
        }
      }
    });

    // 存储该类型的实体
    this.monitorPointsMap.set(monitorType, entities);
    this.visibleMonitorTypes.add(monitorType);

    console.log(`✅ ${monitorType}监测点显示完成, 实际创建:`, entities.length);
  }

  /**
   * 隐藏指定类型的监测点
   */
  hideMonitorType(monitorType) {
    console.log(`🙈 隐藏${monitorType}监测点`);

    const entities = this.monitorPointsMap.get(monitorType);
    if (entities && entities.length > 0) {
      entities.forEach((entity) => {
        try {
          if (entity && entity.destroy) {
            entity.destroy();
          }
        } catch (error) {
          console.warn('销毁实体时出错:', error);
        }
      });
    }

    // 清除存储和状态
    this.monitorPointsMap.delete(monitorType);
    this.visibleMonitorTypes.delete(monitorType);

    console.log(`✅ ${monitorType}监测点已隐藏`);
  }

  /**
   * 检查监测类型是否已显示
   */
  isMonitorTypeVisible(monitorType) {
    return this.visibleMonitorTypes.has(monitorType);
  }

  /**
   * 清除所有监测点
   */
  clearAllMonitorPoints() {
    console.log('🗑️ 清除所有监测点');

    this.visibleMonitorTypes.forEach((monitorType) => {
      this.hideMonitorType(monitorType);
    });

    this.monitorPointsMap.clear();
    this.visibleMonitorTypes.clear();
  }

  /**
   * 设置选中的实体
   */
  setSelectedEntity(entity, entityData) {
    // 清除之前选中实体的样式
    this.clearSelectedEntity();

    // 设置新的选中实体
    this.selectedEntity = entity;
    this.selectedEntityData = entityData;

    // 添加选中样式
    this.applySelectedStyle(entity);
  }

  /**
   * 清除选中的实体
   */
  clearSelectedEntity() {
    if (this.selectedEntity) {
      // 恢复原始样式
      this.restoreOriginalStyle(this.selectedEntity);
      this.selectedEntity = null;
      this.selectedEntityData = null;

      // 关闭弹窗
      this.closeAllPopups();
    }
  }

  /**
   * 检查实体是否已选中
   */
  isEntitySelected(entity) {
    return this.selectedEntity === entity;
  }

  /**
   * 应用选中样式
   */
  applySelectedStyle(entity) {
    if (!entity) return;

    try {
      // 方法1: 通过 style 属性（对于 THING.EARTH.GeoPoint）
      if (entity.style && typeof entity.style.size !== 'undefined') {
        if (!entity.originalSize) {
          entity.originalSize = entity.style.size;
        }
        entity.style.size = entity.originalSize * 1.3;
      }

      // 方法2: 通过 scale 属性（对于其他实体类型）
      else if (entity.scale) {
        if (!entity.originalScale) {
          entity.originalScale = Array.isArray(entity.scale) ? [...entity.scale] : [entity.scale, entity.scale, entity.scale];
        }
        entity.scale = [1.3, 1.3, 1.3];
      }

      // 方法3: 添加高亮效果（如果支持）
      if (entity.outline) {
        entity.outline = true;
        entity.outlineColor = '#00ff00'; // 绿色高亮
      }
    } catch (error) {
      console.warn('⚠️ 应用选中样式失败:', error);
    }
  }

  /**
   * 恢复原始样式
   */
  restoreOriginalStyle(entity) {
    if (!entity) return;

    try {
      // 方法1: 恢复 style.size
      if (entity.style && entity.originalSize !== undefined) {
        entity.style.size = entity.originalSize;
        delete entity.originalSize;
      }

      // 方法2: 恢复 scale
      if (entity.originalScale) {
        entity.scale = entity.originalScale;
        delete entity.originalScale;
      }

      // 方法3: 移除高亮效果
      if (entity.outline !== undefined) {
        entity.outline = false;
        delete entity.outlineColor;
      }
    } catch (error) {
      console.warn('⚠️ 恢复原始样式失败:', error);
    }
  }

  /**
   * 创建监测点位
   */
  createMonitorPoint(monitorItem, monitorType, index) {
    try {
      const modelUrl = this.getMonitorModelUrl(monitorType, monitorItem.equipmentClassify);
      let monitorPoint;

      if (modelUrl) {
        // 使用3D模型创建监测点位
        monitorPoint = new THING.EARTH.GeoPoint({
          name: monitorItem.name || `${monitorType}_${index}`,
          coordinates: THING.EARTH.Utils.convertWgs84ToGcj02([
            parseFloat(monitorItem.longitude),
            parseFloat(monitorItem.latitude),
            parseFloat(monitorItem.height || 0)
          ]),
          style: {
            pointType: THING.EARTH.SymbolType.Model,
            url: modelUrl,
            size: 100, // 模型缩放比例
            keepSize: false // 模型近大远小
          },
          complete: () => {
            this.setupMonitorPointEvents(monitorPoint, monitorItem, monitorType);
          }
        });
      } else {
        // 回退到图标模式
        monitorPoint = new THING.EARTH.GeoPoint({
          name: monitorItem.name || `${monitorType}_${index}`,
          coordinates: THING.EARTH.Utils.convertWgs84ToGcj02([
            parseFloat(monitorItem.longitude),
            parseFloat(monitorItem.latitude),
            parseFloat(monitorItem.height || 0)
          ]),
          style: {
            pointType: THING.EARTH.SymbolType.Image,
            url: this.getMonitorIcon(monitorType, monitorItem.equipmentClassify, monitorItem),
            size: 3,
            keepSize: true
          },
          complete: () => {
            this.setupMonitorPointEvents(monitorPoint, monitorItem, monitorType);
          }
        });
      }

      // 设置用户数据
      if (monitorPoint) {
        monitorPoint.userData = {
          type: 'monitorPoint',
          monitorType: monitorType,
          id: monitorItem.id || `${monitorType}_${index}`,
          data: monitorItem
        };
      }

      return monitorPoint;
    } catch (error) {
      console.error('❌ 创建监测点位失败:', error, monitorItem);
      return null;
    }
  }

  /**
   * 获取监测点模型URL
   */
  getMonitorModelUrl(monitorType, equipmentClassify = null) {
    switch (monitorType) {
      case '压力监测':
        return '/api/models/19024241d30d454ea5fd5dcbe20c052a/0/gltf/';
      case '餐饮场所监测':
        // 餐饮场所监测使用图标，不使用模型
        return null;
      case '激光监测':
        // 根据equipmentClassify返回不同的激光监测模型
        if (equipmentClassify === '22') {
          // 埋地式模型
          return '/api/models/668974f37ded487885dcc836ce34d356/0/gltf/';
        } else if (equipmentClassify === '19') {
          // 壁挂式模型
          return '/api/models/9dcd304aa861466c8a4ac7018e57a806/0/gltf/';
        }
        return null; // 其他情况使用图标
      case '相邻地下空间':
        // 相邻地下空间的equipmentClassify通常是19，使用壁挂式模型
        if (equipmentClassify === '19') {
          // 使用与激光监测壁挂式相同的模型
          return '/api/models/9dcd304aa861466c8a4ac7018e57a806/0/gltf/';
        }
        return null; // 其他情况使用图标
      case '人口密集区':
        // 人口密集区根据equipmentClassify返回不同的处理
        if (equipmentClassify === '22') {
          // 22 - 埋地式，复用激光监测的埋地式模型
          return '/api/models/668974f37ded487885dcc836ce34d356/0/gltf/';
        } else if (equipmentClassify === '3') {
          // 3 - 专用模型
          return '/api/models/A8053CF5930044BD935A546825668900/0/gltf/';
        }
        // 21和26使用图标，返回null
        return null;
      case '扰动风险区域':
        // 扰动风险区域只有设备类型4，使用图标显示
        return null;
      case '预警总数':
        // 预警总数根据warningLevel使用不同图标，不使用3D模型
        return null;
      case '事件处置':
        // 事件处置根据warningLevel使用不同图标，不使用3D模型
        return null;
      case '预警概况':
        // 预警概况根据warningLevel使用不同图标，不使用3D模型
        return null;
      case '设备告警概况':
      case '告警类型统计':
        // 告警相关类型使用固定图标，不使用3D模型
        return null;
      default:
        return null; // 其他类型使用图标
    }
  }

  /**
   * 根据warningLevel获取预警图标
   */
  getWarningLevelIcon(warningLevel) {
    switch (warningLevel) {
      case '1':
        return 'https://static.3dmomoda.com/textures/23073110pgko6zrng3ooqhhmrs1y2pxp.png';
      case '2':
        return 'https://static.3dmomoda.com/textures/23073110weckyus8gh5my4cpsfa4uhhm.png';
      case '3':
        return 'https://static.3dmomoda.com/textures/23073110cutjcwesahtrsmsl1gdeappw.png';
      case '4':
        return 'https://static.3dmomoda.com/textures/23073110jwbxzeysqhiosd87hvglrt3o.png';
      default:
        // 默认使用1级预警图标
        return 'https://static.3dmomoda.com/textures/23073110pgko6zrng3ooqhhmrs1y2pxp.png';
    }
  }

  /**
   * 获取监测点图标
   */
  getMonitorIcon(monitorType, equipmentClassify = null, monitorItem = null) {
    switch (monitorType) {
      case '压力监测':
        return null;
      case '餐饮场所监测':
        // 根据equipmentClassify区分阀门和DTU
        if (equipmentClassify === '16') {
          // 阀门图片
          return 'https://static.3dmomoda.com/textures/23061409im9ofcaqcybfzdfjyckcj0tu.png';
        } else if (equipmentClassify === '20') {
          // DTU图片
          return 'https://static.3dmomoda.com/textures/24032516jmscwhg5pcsxnr0mqkzf5pau.png';
        }
      case '激光监测':
        return null;
      case '相邻地下空间':
        // 相邻地下空间的默认图标
        return 'https://static.3dmomoda.com/textures/24032516jmscwhg5pcsxnr0mqkzf5pau.png';
      case '人口密集区':
        // 人口密集区根据equipmentClassify返回不同图标
        if (equipmentClassify === '21') {
          // 21 - 专用图标
          return 'https://static.3dmomoda.com/textures/24032516kjco3rouvgdqaktezsibpzbc.png';
        } else if (equipmentClassify === '26') {
          // 26 - 专用图标
          return 'https://static.3dmomoda.com/textures/24032516jmscwhg5pcsxnr0mqkzf5pau.png';
        } else if (equipmentClassify === '22' || equipmentClassify === '3') {
          // 22和3使用3D模型，这里不应该被调用，但提供默认图标作为后备
          return 'https://static.3dmomoda.com/textures/24032516jmscwhg5pcsxnr0mqkzf5pau.png';
        }
        // 默认图标
        return 'https://static.3dmomoda.com/textures/24032516jmscwhg5pcsxnr0mqkzf5pau.png';
      case '扰动风险区域':
        // 扰动风险区域设备类型4的专用图标
        if (equipmentClassify === '4') {
          return 'https://static.3dmomoda.com/textures/230731106hetrgbsasfiuwq9lg1zsl2m.png';
        }
        // 默认图标（虽然只有类型4）
        return 'https://static.3dmomoda.com/textures/230731106hetrgbsasfiuwq9lg1zsl2m.png';
      case '预警总数':
      case '事件处置':
      case '预警概况':
        // 预警相关类型根据warningLevel返回不同图标
        return this.getWarningLevelIcon(monitorItem?.warningLevel);
      case '设备告警概况':
      case '告警类型统计':
        // 告警相关类型使用固定图标
        return 'https://static.3dmomoda.com/textures/23073110fhmqk9n1gaoyavpioaiysymc.png';
      default:
        return 'https://static.3dmomoda.com/textures/24032516jmscwhg5pcsxnr0mqkzf5pau.png';
    }
  }

  /**
   * 设置监测点位事件
   */
  setupMonitorPointEvents(monitorPoint, monitorItem, monitorType) {
    // 点击事件
    monitorPoint.on('click', (ev) => {
      this.onMonitorPointClick(monitorPoint, monitorItem, monitorType);
    });

    // 悬停效果（只在未选中时生效）
    monitorPoint.on('mouseenter', () => {
      if (!this.isEntitySelected(monitorPoint)) {
        this.applyHoverStyle(monitorPoint);
      }
    });

    monitorPoint.on('mouseleave', () => {
      if (!this.isEntitySelected(monitorPoint)) {
        this.restoreHoverStyle(monitorPoint);
      }
    });
  }

  /**
   * 应用悬停样式
   */
  applyHoverStyle(entity) {
    if (!entity) return;

    try {
      if (entity.style && typeof entity.style.size !== 'undefined') {
        if (!entity.hoverOriginalSize) {
          entity.hoverOriginalSize = entity.style.size;
        }
        entity.style.size = entity.hoverOriginalSize * 1.15; // 轻微放大
      } else if (entity.scale) {
        if (!entity.hoverOriginalScale) {
          entity.hoverOriginalScale = Array.isArray(entity.scale) ? [...entity.scale] : [entity.scale, entity.scale, entity.scale];
        }
        entity.scale = [1.15, 1.15, 1.15]; // 轻微放大
      }
    } catch (error) {
      console.warn('⚠️ 应用悬停样式失败:', error);
    }
  }

  /**
   * 恢复悬停样式
   */
  restoreHoverStyle(entity) {
    if (!entity) return;

    try {
      if (entity.style && entity.hoverOriginalSize !== undefined) {
        entity.style.size = entity.hoverOriginalSize;
        delete entity.hoverOriginalSize;
      } else if (entity.hoverOriginalScale) {
        entity.scale = entity.hoverOriginalScale;
        delete entity.hoverOriginalScale;
      }
    } catch (error) {
      console.warn('⚠️ 恢复悬停样式失败:', error);
    }
  }

  /**
   * 监测点位点击事件
   */
  onMonitorPointClick(monitorPoint, monitorItem, monitorType) {
    console.log('🎯 监测点位点击事件开始');
    console.log('🎯 monitorPoint:', monitorPoint);
    console.log('🎯 monitorItem:', monitorItem);
    console.log('🎯 monitorType:', monitorType);

    // 获取实体的DOM位置
    const entityPosition = this.getEntityDOMPosition(monitorPoint);
    console.log('🎯 getEntityDOMPosition返回结果:', entityPosition);

    // 根据监测类型映射到对应的弹窗type
    const getPopupType = (monitorType) => {
      const typeMapping = {
        '压力监测': 'MONITOR',
        '激光监测': 'MONITOR',
        '餐饮场所监测': 'MONITOR',
        '相邻地下空间': 'MONITOR',
        '人口密集区': 'MONITOR',
        '扰动风险区域': 'MONITOR',
        '预警总数': 'WARING',
        '事件处置': 'WARING',
        '预警概况': 'WARING',
        '设备告警概况': 'GAOJINGTYPE',
        '告警类型统计': 'GAOJINGTYPE'
      };
      return typeMapping[monitorType] || 'MONITOR';
    };

    // 根据监测类型创建不同的弹窗数据
    let popupData = {
      id: monitorItem.id || `${monitorType}_${Date.now()}`,
      name: monitorItem.name || `${monitorType}点`,
      type: getPopupType(monitorType), // 动态设置弹窗类型
      monitorType: monitorType, // 保留原始监测类型
      status: monitorItem.status || 'normal',
      location: monitorItem.address || '未知位置',
      updateTime: monitorItem.updateTime || new Date().toISOString(),
      geoPosition: {
        longitude: parseFloat(monitorItem.longitude),
        latitude: parseFloat(monitorItem.latitude),
        height: parseFloat(monitorItem.height || 0)
      },
      position: entityPosition, // 使用实体DOM位置
      followMap: true
    };

    console.log('🎯 创建的popupData:', popupData);
    console.log('🎯 popupData.position:', popupData.position);

    // 根据监测类型添加特定数据
    switch (monitorType) {
      case '压力监测':
        popupData.pressure = monitorItem.pressure || 0;
        popupData.unit = monitorItem.unit || 'MPa';
        break;
      case '泄漏监测':
        popupData.gasConcentration = monitorItem.gasConcentration || 0;
        popupData.unit = monitorItem.unit || 'ppm';
        break;
      case '流量监测':
        popupData.flowRate = monitorItem.flowRate || 0;
        popupData.unit = monitorItem.unit || 'm³/h';
        break;
      default:
        popupData.value = monitorItem.value || 0;
        popupData.unit = monitorItem.unit || '';
        popupData.rawData = monitorItem;
        break;
    }

    // 显示弹窗
    this.showMonitorData(popupData);
  }

  destroy() {
    if (this.zoomTimer) {
      clearTimeout(this.zoomTimer);
    }

    if (this.rafId) {
      cancelAnimationFrame(this.rafId);
    }

    this.trackingPopups.clear();

    console.log('🗑️ 优化弹窗管理器已销毁');
  }
}

// ==================== 管道井模型管理 ====================

/**
 * 管道井模型管理器
 */
class PipeWellManager {
  constructor(app) {
    this.app = app;
    this.pipeWells = new Map(); // 存储所有管道井对象
    this.modelUrl = '/api/models/5225064093794cacb23dd770c5e6f9bc/0/gltf/'; // 管道井模型地址

    console.log('🕳️ 管道井管理器初始化完成');
  }

  /**
   * 绘制所有管道井
   */
  drawAll(wellData) {
    console.log('🎨 开始绘制管道井，总数:', wellData.length);

    wellData.forEach((well, index) => {
      this.drawSingle(well, index);
    });

    console.log('✅ 管道井绘制完成');
  }

  /**
   * 绘制单个管道井
   */
  drawSingle(wellData, index) {
    try {
      // 检查必要的坐标数据
      if (!wellData.longitude || !wellData.latitude) {
        console.warn('⚠️ 管道井缺少坐标信息:', wellData);
        return;
      }

      const position = THING.EARTH.Utils.convertWgs84ToGcj02([
        parseFloat(wellData.longitude),
        parseFloat(wellData.latitude),
        parseFloat(wellData.height || 0)
      ]);

      const pipeWell = new THING.EARTH.GeoPoint({
        name: wellData.name || `管道井_${index}`,
        coordinates: position,
        style: {
          pointType: THING.EARTH.SymbolType.Model, // 代表使用模型
          url: this.modelUrl, // 模型 url
          size: 5, // 缩放比例
          keepSize: false // 图标近大远小
        },
        complete: () => {
          this.onModelLoaded(pipeWell, wellData);
        }
      });
      // 存储管道井对象
      this.pipeWells.set(wellData.id || `well_${index}`, {
        object: pipeWell,
        data: wellData
      });
    } catch (error) {
      console.error('❌ 创建管道井失败:', error, wellData);
    }
  }

  /**
   * 模型加载完成后的处理
   */
  onModelLoaded(pipeWell, wellData) {
    // 设置模型属性
    if (pipeWell) {
      // 设置缩放比例
      pipeWell.scale = [1, 1, 1];

      console.log(`✅ 管道井模型渲染完成: ${wellData.name || 'unknown'}`);
    }
  }

  /**
   * 清除所有管道井
   */
  clearAll() {
    this.pipeWells.forEach((wellInfo) => {
      if (wellInfo.object) {
        wellInfo.object.destroy();
      }
    });
    this.pipeWells.clear();
    console.log('🗑️ 已清除所有管道井');
  }

  /**
   * 根据ID获取管道井
   */
  getWellById(id) {
    return this.pipeWells.get(id);
  }

  /**
   * 获取所有管道井
   */
  getAllWells() {
    return Array.from(this.pipeWells.values());
  }

  /**
   * 飞行到指定管道井
   */
  flyToWell(wellId) {
    const wellInfo = this.pipeWells.get(wellId);
    if (wellInfo && wellInfo.object) {
      this.app.camera.flyTo({
        object: wellInfo.object,
        time: 2000
      });
    }
  }
}

// ==================== 应用初始化 ====================

// 全局变量
window.messenger = null;
window.popupManager = null;
window.pipeWellManager = null;

/**
 * 应用初始化
 */
function initializeApp() {
  console.log('🚀 === 应用初始化开始 ===');

  // 1. 初始化通信系统
  window.messenger = new ThingJSMessenger();

  // 2. 初始化弹窗管理器
  window.popupManager = new OptimizedPopupManager(app);

  // 3. 初始化管道井管理器
  window.pipeWellManager = new PipeWellManager(app);

  // 4. 设置消息处理器
  window.popupManager.setupMessageHandlers();

  // 5. 导出全局API
  setupGlobalAPI();

  // 6. 发送加载完成消息
  sendLoadCompleteMessage();
}

/**
 * 设置全局API
 */
function setupGlobalAPI() {
  // 导出便捷方法
  window.showDeviceDetail = (deviceData) => {
    if (window.popupManager) {
      window.popupManager.showDeviceDetail(deviceData);
    } else {
      console.error('❌ 弹窗管理器未初始化');
    }
  };

  window.showMonitorData = (monitorData) => {
    if (window.popupManager) {
      window.popupManager.showMonitorData(monitorData);
    } else {
      console.error('❌ 弹窗管理器未初始化');
    }
  };

  window.showAlarmInfo = (alarmData) => {
    if (window.popupManager) {
      window.popupManager.showAlarmInfo(alarmData);
    } else {
      console.error('❌ 弹窗管理器未初始化');
    }
  };

  window.showWarningInfo = (warningData) => {
    if (window.popupManager) {
      window.popupManager.showWarningInfo(warningData);
    } else {
      console.error('❌ 弹窗管理器未初始化');
    }
  };

  window.closePopup = (popupId) => {
    if (window.popupManager) {
      window.popupManager.closePopup(popupId);
    }
  };

  window.closeAllPopups = () => {
    if (window.popupManager) {
      window.popupManager.closeAllPopups();
    }
  };

  // 通信相关API
  window.sendToVue = (method, data) => {
    if (window.messenger) {
      return window.messenger.sendMessage(method, data);
    }
  };

  window.notifyVue = (method, data) => {
    if (window.messenger) {
      window.messenger.notify(method, data);
    }
  };

  // 管道井相关API
  window.drawPipeWells = (wellData) => {
    if (window.pipeWellManager) {
      window.pipeWellManager.clearAll(); // 先清除已有的
      window.pipeWellManager.drawAll(wellData);
    } else {
      console.error('❌ 管道井管理器未初始化');
    }
  };

  window.clearPipeWells = () => {
    if (window.pipeWellManager) {
      window.pipeWellManager.clearAll();
    }
  };

  window.flyToPipeWell = (wellId) => {
    if (window.pipeWellManager) {
      window.pipeWellManager.flyToWell(wellId);
    }
  };

  console.log('✅ 全局API设置完成');
}

/**
 * 发送加载完成消息
 */
function sendLoadCompleteMessage() {
  // 确保ThingJS完全准备好后再发送消息
  setTimeout(() => {
    const loadInfo = {
      message: 'ThingJS应用加载完成',
      timestamp: new Date().toISOString(),
      appInfo: {
        version: '2.1',
        mapType: 'EARTH.Map',
        camera: {
          position: app.camera.position,
          target: app.camera.target
        }
      },
      capabilities: {
        popupSystem: true,
        mapFollow: true,
        deviceInteraction: true,
        optimizedCommunication: true
      }
    };

    window.messenger.notify('ThingJS加载完成', loadInfo);
  }, 2000); // 等待2秒确保所有组件都已初始化
}

// ==================== 便捷函数 ====================

/**
 * 绘制管道井（全局函数）
 * @param {Array} wellData 管道井数据数组
 */
function drawPipeWells(wellData) {
  if (window.pipeWellManager) {
    window.pipeWellManager.drawAll(wellData);
  } else {
    console.error('❌ 管道井管理器未初始化');
  }
}

// ==================== 初始化完成 ====================

console.log('🎉 === ThingJS优化版本加载完成 ===');
console.log('📋 功能包括：');
console.log('  ✅ 优化的Vue弹窗系统');
console.log('  ✅ 改进的通信机制（消息确认、重试、节流）');
console.log('  ✅ 地图拖动跟随');
console.log('  ✅ 设备交互');
console.log('  ✅ 管道井模型绘制');
console.log('  ✅ 性能优化');
console.log('');
console.log('🔧 使用方法:');
console.log('  showDeviceDetail(deviceData)   // 显示设备详情');
console.log('  showMonitorData(monitorData)   // 显示监测数据');
console.log('  showAlarmInfo(alarmData)       // 显示报警信息');
console.log('  showWarningInfo(warningData)   // 显示预警信息');
console.log('  closePopup(popupId)            // 关闭指定弹窗');
console.log('  closeAllPopups()               // 关闭所有弹窗');
console.log('  drawPipeWells(wellData)        // 绘制管道井模型');
console.log('  clearPipeWells()               // 清除所有管道井');
console.log('  flyToPipeWell(wellId)          // 飞行到指定管道井');
console.log('  sendToVue(method, data)        // 发送消息到Vue（带响应）');
console.log('  notifyVue(method, data)        // 通知Vue（不需要响应）');
console.log('  testPopup(type)                // 🧪 测试弹窗功能');
console.log('');
console.log('🧪 测试弹窗:');
console.log('  testPopup()                    // 测试监测数据弹窗');
console.log('  testPopup("device-detail")     // 测试设备详情弹窗');
console.log('  testPopup("alarm-info")        // 测试报警信息弹窗');
console.log('  testWarningPopup()             // 测试预警信息弹窗');
console.log('  testDifferentTypes()           // 测试不同类型弹窗');

// 测试预警弹窗功能
window.testWarningPopup = () => {
  const centerX = window.innerWidth / 2;
  const centerY = window.innerHeight / 2;

  const testWarningData = {
    id: `warning_test_${Date.now()}`,
    warningType: '气体泄漏预警',
    warningLevel: '2',
    level: 'high',
    status: 'active',
    title: '高危区域气体泄漏预警',
    geoPosition: {
      longitude: 117.0983,
      latitude: 36.6512,
      height: 10
    },
    position: { x: centerX, y: centerY },
    followMap: true,
    info: {
      typeName: '气体泄漏预警',
      statusName: '待处理',
      createTime: new Date().toISOString(),
      durationTime: '2小时30分钟',
      occurrenceAddress: '泉城路123号附近',
      workOrderInfoUrl: 'https://example.com/work-order/123'
    },
    warningTime: new Date().toISOString(),
    location: '泉城路123号附近',
    message: '检测到该区域气体浓度异常升高，可能存在泄漏风险，请立即派遣专业人员进行现场检查。',
    riskLevel: 'high',
    probability: 85,
    impact: '中等',
    response: '1. 立即疏散周边人员\n2. 切断相关气源\n3. 通知专业维修团队\n4. 现场警戒并监测'
  };

  if (window.popupManager) {
    window.popupManager.showWarningInfo(testWarningData);
  } else {
    console.error('❌ 弹窗管理器未初始化');
  }
};

// 测试不同类型弹窗功能
window.testDifferentTypes = () => {
  const centerX = window.innerWidth / 2;
  const centerY = window.innerHeight / 2;

  const testTypes = [
    { type: 'MONITOR', monitorType: '压力监测', name: '压力监测点' },
    { type: 'WARING', monitorType: '预警总数', name: '预警总数点' },
    { type: 'GAOJINGTYPE', monitorType: '设备告警概况', name: '设备告警概况点' },
    { type: 'GAOJINGTYPE', monitorType: '告警类型统计', name: '告警类型统计点' }
  ];

  testTypes.forEach((testCase, index) => {
    setTimeout(() => {
      const testData = {
        id: `test_${testCase.type}_${Date.now()}`,
        name: testCase.name,
        type: testCase.type,
        monitorType: testCase.monitorType,
        status: 'normal',
        location: '测试位置',
        updateTime: new Date().toISOString(),
        geoPosition: {
          longitude: 117.0983,
          latitude: 36.6512,
          height: 10
        },
        position: {
          x: centerX + index * 50,
          y: centerY + index * 50
        },
        followMap: true
      };

      console.log(`🧪 测试 ${testCase.type} 类型弹窗:`, testData);

      if (window.popupManager) {
        window.popupManager.showMonitorData(testData);
      } else {
        console.error('❌ 弹窗管理器未初始化');
      }
    }, index * 1000);
  });
};
